<template>
  <div class="medical-editor">
    <slot name="toolbar">
      <MedicalToolbar />
    </slot>

    <div class="editor-content flex">
      <slot name="navigator">
        <MedicalNavigator v-if="showNavigator" />
      </slot>

      <div class="flex-1">
        <SlateEditor :value="editorValue" @change="onEditorChange">
          <Editable 
          :placeholder="placeholder" 
          class="min-h-[600px] p-6 bg-white border rounded-md shadow-sm" 
          :style="{ fontFamily: fontSettings.fontFamily, fontSize: `${fontSettings.fontSize}px` }" />
        </SlateEditor>
      </div>
    </div>

    <slot name="statusbar">
      <StatusBar />
    </slot>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { createEditor } from "slate";
import { withReact } from "slate-react";
import { SlateEditor, Editable } from "slate-vue";
import { useEditorStore } from "../stores/editorStore";
import { MedicalElement } from "../types/medicalTypes";
import SlateWrapper from './SlateWrapper';
import { h } from 'vue';

const props = defineProps({
  value: {
    type: Array as () => MedicalElement[],
    required: false,
  },
  showNavigator: {
    type: Boolean,
    default: true,
  },
  placeholder: {
    type: String,
    default: "请输入医疗文档内容...",
  },
});

const emit = defineEmits(["change", "update:value"]);

const editorStore = useEditorStore();
const editor = ref(createEditor());

// 字体设置
const fontSettings = computed(() => ({
  fontFamily: editorStore.config.fontFamily || editorStore.config.defaultFontFamily || "SimSun",
  fontSize: editorStore.config.fontSize || editorStore.config.defaultFontSize || 14,
}));

// 编辑器内容
const editorValue = computed({
  get() {
    return props.value || editorStore.editorValue || [];
  },
  set(value) {
    try {
      editorStore.setEditorValue(value);
      emit("change", value);
      emit("update:value", value);
    } catch (error) {
      console.error("Error setting editor value:", error);
    }
  },
});

onMounted(() => {
  // 初始化编辑器
  try {
    editor.value = withReact(editor.value);
  } catch (err: unknown) {
    if (err instanceof Error && !err.message.includes('Permission denied to access property "nodeType"')) {
      console.error('Editor initialization error:', err);
    }
  }
});

const onEditorChange = (value: MedicalElement[]) => {
  editorValue.value = value;
};
</script>
